/**
 * create by gby 20180902
 */
$(function () {
    obj.init();
});

var obj = new function () {
    'use strict';
    return {
        dataGrid: null,
        params: {
            ids: null
        },
        type:null,
        tactic:null,
        userType:null,
        init: function () {
            this.serverType = xhTool.getQuery('serverType');
            this.dataGrid = new xhDataGrid($('#List'), 'Server_config/getMicroServerConfigData', {serverType: this.serverType});
            this.dataGrid.parseToolbar().init();
            xhTool.bindDocKeyDown($('#bt_list_search'));
            this.params.ids = this.dataGrid.getSelectValues('id');
            this.form = new xhForm($('#xh_form'));
            this.form.parse().bindRequired($('#bt_form_add,#bt_form_edit'));
            this.tactic = $('#tactic').val();
            $('.school-box, .server-box, .return-box, .custom-div, .tactic-box').hide();
            this.funObj().bindDataGridEvent();//有修改权限，双击打开表单
            this.listener();
        },
        listener: function () {
            var $this = this;
            $('#schoolId').select2(
                {
                    placeholder: "请选择学校"
                }
            );
            if($this.serverType == 'SCHOOL'){
                $('.custom-div, .school-box').show();
                $(' .server-box, .return-box, .tactic-box').hide();
            }else if($this.serverType == 'APP'){
                $('.tactic-box, .server-box').show();
                $('.return-box, .custom-div, .school-box').hide();
            }else {
                $('.return-box, .school-box').show();
                $('.custom-div, .tactic-box, .server-box').hide();
            }
            xhTool.bindDocKeyDown(
                // 绑定搜索事件
                $('#bt_list_search').click(function () {
                    $this.funObj().search();
                })
            );
            // 返回
            $('#bt_form_back').click(function () {
                xhExtra.backToList();
            });
            // 重置
            $('#bt_form_reset').click(function () {
                $.overtFun.clickResetForm();
            });
            // 新增
            $('#bt_list_add').click(function () {
                var customClone =  $('.custom-clone').eq(0).clone();
                $('.custom-clone')._remove();
                $('#addCustomBtn').parent().parent().before(customClone);
                $.overtFun.clickAddList($this.dataGrid);
                $('#bt_form_add, #bt_form_edit').removeClass('disabled');
            });
            // 删除
            $('#bt_list_del').click(function(){
                $this.funObj().changeStatu('del', '确定删除吗？');
            });
            // 增加提交
            $('#bt_form_add').click(function () {
                $this.funObj().saveData('add');
            });
            // 更新提交
            $('#bt_form_edit').click(function () {
                $this.funObj().saveData('edit');
            });
            //添加自定义属性
            $("#addCustomBtn").click(function () {
                $this.funObj().addCustom();
            });
        },
        funObj: function () {
            var $this = this;
            return {
                bindDataGridEvent: function () {
                    $this.dataGrid.onLoadSuccess = function (data) {
                        if($this.serverType == 'SCHOOL'){
                            $("td[field=serverType], td[field=returnType]").hide();
                            $("td[field=schoolId]").show();
                        }else if($this.serverType == 'APP'){
                            $("td[field=serverType], td[field=returnType]").show();
                           $("td[field=schoolId], td[field=returnType]").hide();
                        }else {
                            $("td[field=serverType]").hide();
                           $("td[field=schoolId]").show();
                        }
                        if (xhExtra.checkError(data)) return false;
                        if (data.rows.length <= 0) return false;
                    };
                    $this.dataGrid.onDblClickRow = function (rowIndex, rowData) {
                        xhExtra.ajaxRequest('Server_config/getMicroServerConfigOne/', {id:rowData.id,type:$this.serverType}, {}, function (data) {
                            $this.funObj().fillData(data);
                            xhExtra.forwardToForm(true);
                        });
                    };
                    $('#bt_form_add, #bt_form_edit').removeClass('disabled');
                },
                // 搜索
                search: function () {
                    var keyword = xhExtra.getValue($('#List_Search_keyword'));
                    var schoolId = xhExtra.getValue($('#List_Search_schoolId'));
                    var status = $('#List_Search_status').combobox('getValue');
                    $this.dataGrid.reload({keyword: keyword, schoolId: schoolId, status: status});
                },
                // 删除，启用，停止
                changeStatu: function (status, msg) {
                    var url = '';
                    $this.params.ids = $this.dataGrid.getSelectValues('id');
                    if (JSON.stringify($this.params.ids) === '[]') {
                        window.top.xhTop.showError('未选中记录!');
                        return false;
                    }
                    switch(status){
                        case 'del':
                            url = 'Server_config/deleteMicroServerConfig';
                            break;
                        case 'start':
                            url = 'Server_config/startMicroServerConfig';
                            break;
                        case 'stop':
                            url = 'Server_config/stopMicroServerConfig';
                            break;
                    }
                    window.top.swal({
                        title: msg,
                        showCancelButton: true,
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        showLoaderOnConfirm: true
                    }).then(function (result) {
                        xhExtra.ajaxRequest(url, {ids: $this.params.ids, desc: result, type:$this.serverType}, {success: true, table: $this.dataGrid});
                    },function () {

                    });
                },

                // 提交
                saveData: function (target) {
                    var url = '';
                    switch (target) {
                        case 'add':
                            url = 'Server_config/registerMicroServerConfig';
                            break;
                        case 'edit':
                            url = 'Server_config/updateMicroServerConfig';
                            break;
                    }

                    $this.tactic = $("#tactic").val();
                    if($this.serverType == 'SCHOOL') {
                        if($('.customType').val()=='') {
                            window.top.xhTop.showError('自定义属性必填!');
                            return false;
                        }
                    } else if($this.serverType == 'APP') {
                        if($('#serverType').val()=='') {
                            window.top.xhTop.showError('服务编码必填!');
                            return false;
                        }
                    }
                    $this.form.submit(url,{type: $this.serverType},function (res) {
                        if(xhExtra.checkError(res)){
                            return false;
                        }
                        window.top.xhTop.showSuccess(res.msg);
                        $.overtFun.clickBackForm();
                        $this.dataGrid.reload();
                        $('#bt_form_add, #bt_form_edit').removeClass('disabled');
                    },{check:false})
                },

                // 判断是否为正确的ip
                checkIp: function (obj) {
                    var reSpaceCheck = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/;
                    if (reSpaceCheck.test(obj))
                    {
                        obj.match(reSpaceCheck);
                        if (RegExp.$1<=255&&RegExp.$1>=0
                            &&RegExp.$2<=255&&RegExp.$2>=0
                            &&RegExp.$3<=255&&RegExp.$3>=0
                            &&RegExp.$4<=255&&RegExp.$4>=0)
                        {
                            return true;
                        } else
                            {
                                return false;
                            }
                    } else
                        {
                            return false;
                        }
                },
                // 判断端口填写是否正确
                isPort: function (port) {
                    var parten=/^(\d)+$/g;
                    if (parten.test(port)&&parseInt(port)<=65535&&parseInt(port)>0)
                    {
                        return true;
                    } else
                        {
                        return false;
                        }
                },
                addCustom:function () {
                    var customClone =  $('.custom-clone').eq(0).clone();
                    customClone.css('display','table-row');
                    $('.custom-clone:last').after(customClone);
                },
                fillData:function (data) {
                    var customClone =  $('.custom-clone').eq(0).clone();
                    $('.custom-clone')._remove();
                    $('#addCustomBtn').parent().parent().before(customClone);
                    $this.form.reset().fill(data);
                    $("#schoolId").val(data.schoolId).select2();
                    if(data.type == 'SCHOOL'){
                        var customClone =  $('.custom-clone').eq(0).clone();
                        for(var i=0;i<data.customConfigList.length;i++) {
                            var customCloneTr = customClone.clone();
                            $('#addCustomBtn').parent().parent().before(customCloneTr);
                        }
                        for(var i=0;i<data.customConfigList.length;i++){
                            var customType = data.customConfigList[i].customType;
                            var serverId = data.customConfigList[i].serverId;
                            $($('.custom-box .custom-clone .customType')[i]).val(customType);
                            $($('.custom-box .custom-clone .serverId')[i]).val(serverId);
                        }
                        $('.custom-clone:last').css('display','none');
                    }else{
                        $('.custom-box').css('display','none');
                    }
                    $('#addCustomBtn').val('添加');
                }
            }
        }
    }
};